<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * topic controller
 */
class Subject extends Admin_Controller
{
    protected $permissionCreate = 'Topic.Subject.Create';
    protected $permissionDelete = 'Topic.Subject.Delete';
    protected $permissionEdit   = 'Topic.Subject.Edit';
    protected $permissionView   = 'Topic.Subject.View';

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        
        $this->auth->restrict($this->permissionView);
        $this->load->model('topic/topic_model');
        $this->load->model('area/area_model');
        
        $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");
        
        Template::set_block('sub_nav', 'topic/_sub_nav');
        
        Assets::add_css(array('plugins/ckeditor/samples/css/samples.css',
                            'plugins/ckeditor/samples/toolbarconfigurator/lib/codemirror/neo.css', 
                            'plugins/iCheck/all.css', 
                            'plugins/select2/select2.min.css',
                            'plugins/datepicker/datepicker3.css'));
        Assets::add_js(array(Template::theme_url('plugins/select2/select2.full.min.js'), 
                            Template::theme_url('plugins/iCheck/icheck.min.js'), 
                            Template::theme_url('plugins/datepicker/bootstrap-datepicker.js'), 
                            Template::theme_url('plugins/ckeditor/ckeditor.js'),
                            Template::theme_url('plugins/ckeditor/samples/js/sample.js'),
                            Template::theme_url('js/plupload-2.1.1/plupload.full.min.js'),
                            Template::theme_url('js/plupload-2.1.1/i18n/zh_CN.js'), 
                            Template::theme_url('js/qiniu.js'),
                            Template::theme_url('plugins/thickbox/thickbox3.js')
                            ));
        Assets::add_js('codeigniter-csrf.js');
        Assets::add_module_js('topic', 'topic.js');

    }

    /**
     * Display a list of subject data.
     *
     * @return void
     */
    public function index($filter = 'all', $offset = 0)
    {
        // Deleting anything?
        if (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);
            $checked = $this->input->post('checked');
            if (is_array($checked) && count($checked)) {

                // If any of the deletions fail, set the result to false, so
                // failure message is set if any of the attempts fail, not just
                // the last attempt

                $result = true;
                foreach ($checked as $pid) {
                    $deleted = $this->topic_model->delete($pid);
                    if ($deleted == false) {
                        $result = false;
                    }
                }
                if ($result) {
                    Template::set_message(count($checked) . ' ' . lang('subject_delete_success'), 'success');
                } else {
                    Template::set_message(lang('subject_delete_failure') . $this->topic_model->error, 'error');
                }
            }
        }
        $where = 'deleted = 0 and status = 2';
        //已发布数目
        $totalTrashNum = $this->topic_model->where($where)->count_all();
        Template::set('totalTrashNum', $totalTrashNum);
        // 草稿总数目
        $rubishNum = $this->topic_model->where("deleted = 0 and status = 1")->count_all();
        Template::set('rubishNum', $rubishNum);
        if($this->input->get('status')){
            $status = $this->input->get('status');
            $where = "status = $status and deleted = 0";
            $listType = $status;
            $totalTrashNum = $this->topic_model->where($where)->count_all();
        }
        //分页
        $pagerUriSegment = 6;
        $pagerBaseUrl = site_url(SITE_AREA . '/subject/topic/index') . '/';
        
        $limit  = $this->settings_lib->item('site.list_limit') ?: 10;
        $this->load->library('pagination');
        $this->pager['base_url']    = $pagerBaseUrl.$filter."/";
        $this->pager['total_rows']  = $totalTrashNum;
        $this->pager['per_page']    = $limit;
        $this->pager['uri_segment'] = $pagerUriSegment;

        $this->pagination->initialize($this->pager);
        $this->topic_model->limit($limit, $offset);

        $records = $this->topic_model->where($where)->find_all();
        // 处理数据
        if($records){
            foreach ($records as $key => $value) {
                $cityArr = $this->area_model->find($value->city);
                $records[$key]->cityname = $cityArr->area_name;
                // 状态
                $records[$key]->showstatus = $value->status == 2 ? "已发布" : "草稿";
            }
        }

        Template::set('type', isset($listType) ? $listType : 2);
        // dump($records);exit();
        Template::set('records', $records);

        Template::render();
    }

    /**
     * Create a subject object.
     *
     * @return void
     */
    public function create()
    {

        $this->auth->restrict($this->permissionCreate);
        
        if (isset($_POST['save'])) {
            if ($insert_id = $this->save_subject()) {
                log_activity($this->auth->user_id(), lang('subject_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'subject');
                Template::set_message(lang('subject_create_success'), 'success');

                redirect(SITE_AREA . '/subject/topic');
            }

            // Not validation error
            if ( ! empty($this->topic_model->error)) {
                Template::set_message(lang('subject_create_failure') . $this->topic_model->error, 'error');
            }
        }
        //获取所有的城市
        $city = $this->area_model->getcities();
        Template::set('city', $city);

        Template::set('toolbar_title', lang('subject_action_create'));
        
        Template::render();
    }
    /**
     * Allows editing of subject data.
     *
     * @return void
     */
    public function edit()
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('subject_invalid_id'), 'error');

            redirect(SITE_AREA . '/subject/topic');
        }
        
        elseif (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);

            if ($this->topic_model->delete($id)) {
                log_activity($this->auth->user_id(), lang('subject_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'subject');
                Template::set_message(lang('subject_delete_success'), 'success');

                redirect(SITE_AREA . '/subject/topic');
            }

            Template::set_message(lang('subject_delete_failure') . $this->topic_model->error, 'error');
        }
        $records = $this->topic_model->find($id);
        // $records->whole_url = site_url($records->url);

        // dump($records);exit();
        Template::set('subject', $records);

        $url = site_url("subject/");
        Template::set('url', $url);

        Template::set('toolbar_title', lang('subject_action_create'));
        //获取所有的城市
        $city = $this->area_model->getcities();
        Template::set('city', $city);

        Template::set('toolbar_title', lang('subject_edit_heading'));
        Template::render();
    }
    //添加分类及标签
    public function add_type(){
        $postData = $this->input->post();
        if($postData){
            $data['tag_name'] =  isset($postData['subject_type'])?$postData['subject_type']:"";
            // echo json_encode($data);exit();

            $type= isset($postData['tag_type'])?$postData['tag_type']:2;
            if($type == 1){
                $data['is_new_cate'] = 1;
                $id = $this->tags_model->insert($data);

                if ($id) {
                    $reback = array('id'=>$id,'name'=>$data['tag_name'],'type'=>1);
                    echo json_encode($reback);
                    exit();
                }else{
                    echo 502;
                }
            }else{
                $data['is_new_cate'] = 0;

                $id = $this->tags_model->insert($data);

                if ($id) {
                    $reback = array('id'=>$id,'name'=>$data['tag_name'],'type'=>2);
                    echo json_encode($reback);
                    exit();
                }else{
                    echo 502;
                }
            }
            

        }
    }
    //--------------------------------------------------------------------------
    // !PRIVATE METHODS
    //--------------------------------------------------------------------------
    public function save(){
        $postData = $this->input->post();
        // dump($postData);exit();
        if($postData) {
            $data['title'] = isset($postData['title'])?$postData['title']:"";
            $data['content'] = isset($postData['stem'])?$postData['stem']:"";
            $data['source_pic'] = isset($postData['img_url'])?$postData['img_url']:"";//缩略图
            $data['city'] = isset($postData['city'])?$postData['city']:0;

            $data['status'] = $fabu_zhuangtai = isset($postData['fb_status'])?$postData['fb_status']:2;
            $data['seo_title'] = isset($postData['seo_title'])?$postData['seo_title']:"";
            $data['seo_keywords'] = isset($postData['seo_keywords'])?$postData['seo_keywords']:"";
            $data['seo_description'] = isset($postData['seo_description'])?$postData['seo_description']:"";

            $type = isset($postData['action'])?$postData['action']:1; //1新增  2修改
            $id = isset($postData['topic_id'])?$postData['topic_id']:"";
            // dump($data);exit();
            $data['create_time']=date("Y-m-d H:i:s",time());
            // dump($data);exit();
            //保存
            if($id && $type == 2){
                //修改操作
                $res = $this->topic_model->update($id,$data);
            }else{
                //新增操作
                $id = $this->topic_model->insert($data);
            }
            //保存新闻的标签
            if($id){
                echo 1; exit();
            }else{
                echo 2; exit();
            }
        }

    }
    /**
     * Save the data.
     *
     * @param string $type Either 'insert' or 'update'.
     * @param int    $id   The ID of the record to update, ignored on inserts.
     *
     * @return boolean|integer An ID for successful inserts, true for successful
     * updates, else false.
     */
    private function save_subject($type = 'insert', $id = 0)
    {
        if ($type == 'update') {
            $_POST['id'] = $id;
        }

        // Validate the data
        $this->form_validation->set_rules($this->topic_model->get_validation_rules());
        if ($this->form_validation->run() === false) {
            return false;
        }

        // Make sure we only pass in the fields we want
        
        $data = $this->topic_model->prep_data();

        // Additional handling for default values should be added below,
        // or in the model's prep_data() method
        
        
        $return = false;
        if ($type == 'insert') {
            $id = $this->topic_model->insert($data);

            if (is_numeric($id)) {
                $return = $id;
            }
        } elseif ($type == 'update') {
            $return = $this->topic_model->update($id, $data);
        }

        return $return;
    }
    //更改新闻状态
    public function changestatus(){
         $id = $this->uri->segment(5);
         $type= $this->uri->segment(7);
        if($id && $type){
            if($type==1){
                $data['status'] = 3;
                $res= $this->topic_model->update($id, $data);
                //dump($res);exit();
                redirect(SITE_AREA . '/subject/topic');
            }
            if($type ==2){
                $data['status'] = 1;
                $this->topic_model->update($id, $data);
                redirect(SITE_AREA . '/subject/topic');
            }
          if($type ==3){
                $data['status'] = 5;
                $this->topic_model->update($id, $data);
                redirect(SITE_AREA . '/subject/topic');
            }
        }

    }
    //上传新闻图片
    public function do_upload()
    {
        $config=array(); 
        $errRequestFunction = "错误的功能调用请求"; //错误的功能调用请求
        $errRequestFile = "错误的文件调用请求"; //"错误的文件调用请求"
        $errFileType = "错误的文件类型"; //"错误的文件类型！"
        $errUpfile = "文件上传失败，请检查上传目录设置和目录读写权限t"; //"文件上传失败，请检查上传目录设置和目录读写权限"
        $uploadExceed = "上传的文件不能超过"; //"上传的文件不能超过"
        $config = array ();
        $config ['type'] = array ("flash", "img" ); //上传允许type值
        $config ['img'] = array ("jpg", "bmp", "gif" ,"png","jpeg"); //img允许后缀
        $config ['flash'] = array ("flv", "swf" ); //flash允许后缀
        $config ['flash_size'] = 2000; //上传flash大小上限 单位：KB
        $config ['img_size'] = 5000; //上传img大小上限 单位：KB
        $config ['message'] = "上传成功!"; //上传成功后显示的消息，若为空则不显示上传成功
        $config ['name'] = time (); //上传后的文件命名规则 这里以unix时间戳来命名
        $config ['flash_dir'] = $_SERVER['DOCUMENT_ROOT']."/b2c/upload"; //上传flash文件地址 采用绝对地址 方便upload.php文件放在站内的任何位置后面不加"/",上传的文件将放在网站根目录下的upload文件夹下
        $config ['img_dir'] = $_SERVER['DOCUMENT_ROOT']."/upload"; //上传img文件地址 采用绝对地址 采用绝对地址 方便upload.php文件放在站内的任何位置后面不加"/"，上传的文件将放在网站根目录下的upload文件夹下
        $config ['site_url'] = ""; //网站的网址这与图片上传后的地址有关 最后不加"/" 可留空
        //没有文件夹时则创建
        //$this->isDirAll($config ['flash_dir']);
        $this->isDirAll($config ['img_dir']);
        //文件上传 

        //判断是否是非法调用
            $cate = $_GET['cate'];
            if (empty ( $_GET ['CKEditorFuncNum'] ))
                $this->mkhtml ( 1, "", $errRequestFunction );
            $fn = $_GET ['CKEditorFuncNum'];
            if (! in_array ( $_GET ['type'], $config ['type'] ))
                $this->mkhtml ( 1, "", $errRequestFile );
            $type = $_GET ['type'];
            if (is_uploaded_file ( $_FILES ['upload'] ['tmp_name'] )) {
                //判断上传文件是否允许
                $filearr = pathinfo ( $_FILES ['upload'] ['name'] );
                $filetype = $filearr ["extension"];
                if (! in_array ( $filetype, $config [$type] ))
                    $this->mkhtml ( $fn, "", $errFileType );
                    //判断文件大小是否符合要求
                if ($_FILES ['upload'] ['size'] > $config [$type . "_size"] * 1024)
                    $this->mkhtml ( $fn, "", $uploadExceed . $config [$type . "_size"] . "KB！" );
                    $file_abso = $config [$type . "_dir"] . "/" .$cate."/". $config ['name'] . "." . $filetype;
                //$file_abso = $config [$type . "_dir"] . "/" . $config ['name'] . "." . $filetype;
                $file_host = $file_abso;
                $file_path = "/upload/" .$cate."/". $config ['name'] . "." . $filetype;//这里的/upload/根据你上传文件的目录进行调整
                if (move_uploaded_file ( $_FILES ['upload'] ['tmp_name'], $file_host )) {
                    $this->mkhtml ( $fn, $config ['site_url'] . $file_path, $config ['message'] );
                } else {
                    $this->mkhtml ( $fn, "", $errUpfile . $file_host );
                }
            }
        }

       //输出js调用
        private function mkhtml($fn, $fileurl, $message) {
            $str = '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction(' . $fn . ', "' . $fileurl .'" , "'. $message .'");</script>';           
            exit ( $str );
        }
         
        private  function isDirAll($dir) {
            if (! is_dir ( $dir )) {
                $dirArr = explode ( "/", $dir );
                $mkDir = "";
                for($i = 0; $i < count ( $dirArr ); $i ++) {
                    if ($dirArr [$i] != "") {
                        $mkDir .= '/' . $dirArr [$i];
                        $this->isMkDir ( $mkDir );
                    }
                }
            }
        }
         
       private  function isMkDir($dir = "") {
            if (! is_dir ( $dir )) {
                @mkdir ( $dir, 0777 );
            }
        }

        /**
         * 一键发布
         */
        public function publish(){
            $id = $this->uri->segment(5);
            if(empty($id)) exit('参数缺失');
            $data['status'] = 2;
            $res = $this->topic_model->update($id,$data);
            if($res){
                Template::set_message('一键发布成功');
                redirect(SITE_AREA . '/subject/topic');
            }
        }








}